#include "System.h"

MyFILE* BuyFILE()
{
	return (MyFILE*) malloc(sizeof(MyFILE));
}

MyFILE* MyFopen(const char* path ,const char*  mod)
{
	int id = 0;

	if(strcmp(mod,"w") == 0)
	{
		id = open(path,O_CREAT | O_WRONLY);
	}
	else if(strcmp(mod,"r") == 0)
	{
		id = open(path,O_RDONLY);
	}
	else if(strcmp(mod,"a") == 0)
	{
		id = open(path,O_CREAT | O_APPEND);
	}
	else
	{
		printf("无支持的选项！\n");
	}
	
	if(id < 0)
	{
		printf("打开文件出现了错误！\n");
		exit(1);
	}

	MyFILE* ret = BuyFILE();

	ret->fd = id;

	return ret;
}

void MyFflush(MyFILE* pf)
{
	write(pf->fd,pf->buffer,(pf->bufferlen));
}

void MyWrite(MyFILE* pf , const char* str)
{
	// 说明没有要写的东西。
	if(str == NULL || str[0] == '\0')
	{
		return ;
	}

	// 全刷新
	if((pf->bufferlen + strlen(str)) > MAX)
	{
		MyFflush(pf);
		write(pf->fd,str,strlen(str));

		return ;
	}
	// 行刷新
	else if(str[strlen(str) - 1] == '\n')
	{
		MyFflush(pf);
		write(pf->fd,str,strlen(str));

		return ;
	}

	strcpy(pf->buffer,str);
	pf->bufferlen = strlen(str);

}

void MyClose(MyFILE* pf)
{
	close(pf->fd);

	free(pf);
}
